package patrol.mobile.com.mobilepatrol.activity.monitor;

import android.app.Activity;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.imagepicker.bean.ImageItem;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.adapter.XjMingxiAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.MingxiMoBanBean;
import patrol.mobile.com.mobilepatrol.bean.OrgPostTemplateListBean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.bean.User;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.FileUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.LogUtile;
import patrol.mobile.com.mobilepatrol.utils.LuBanHelper;
import patrol.mobile.com.mobilepatrol.utils.ToastUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;

import static patrol.mobile.com.mobilepatrol.utils.SPUtils.get;

public class XjMingXiMuBanActivity extends BaseActivity {
    @BindView(R.id.detailName)
    TextView detailName;
    @BindView(R.id.detailTime)
    TextView detailTime;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    private MingxiMoBanBean mingxiMoBanBean;
    private XjMingxiAdapter xjMingxiAdapter;
    private String xunjianren;
    private String riqi;
    private List<String> imgUUIDs = new ArrayList<>();
    ArrayList<ImageItem> selImageList;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_mingxi_moban_layout;
    }

    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {
        super.initTitle();
        selImageList = new ArrayList<>();
        xunjianren = getIntent().getStringExtra("xunjianren");
        riqi = getIntent().getStringExtra("riqi");
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("明细页面列表");
        tv_right_title.setVisibility(View.VISIBLE);
        tv_right_title.setText("上传");
        tv_right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit();
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        detailName.setText("巡检人:" + xunjianren);
        detailTime.setText("日期:" + riqi);
        getHttpData();
    }

    /**
     * 获取数据
     */
    private void getHttpData() {
        HashMap<String, String> hashMap = new HashMap();
        HttpSender sender = new HttpSender(this, baseUrl, Urls.getJiankkElefailinsprecDivTemplateList);
        sender.requestPost(hashMap, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                mingxiMoBanBean = new Gson().fromJson(response, MingxiMoBanBean.class);
                manageData(mingxiMoBanBean);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(XjMingXiMuBanActivity.this));
                mRecyclerView.setAdapter(xjMingxiAdapter = new XjMingxiAdapter(mingxiMoBanBean));
                xjMingxiAdapter.setChildAdapterItemClickListener(new XjMingxiAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        startActivityForResult(new Intent(v.getContext(), XjMingXiMuDetailActivity.class)
                                        .putExtra("data", mingxiMoBanBean)
                                        .putExtra("position", position)
                                , 1);
                    }
                });
            }
        });
    }

    private void manageData(MingxiMoBanBean bean) {
        List<MingxiMoBanBean.ParentBean> parentBeanList = new ArrayList<>();
        int i = 0;
        int j = 0;
        MingxiMoBanBean.ParentBean parentBean;
        List<MingxiMoBanBean.ListBean> listBeanList;
        for (; i < bean.getList().size(); i++) {
            parentBean = new MingxiMoBanBean.ParentBean();
            listBeanList = new ArrayList<>();
            parentBean.setProLarge(bean.getList().get(i).getPosition().trim());
            listBeanList.add(bean.getList().get(i));
            j = i + 1;
            for (; j < bean.getList().size(); j++) {
                if (bean.getList().get(i).getPosition().trim().equals(bean.getList().get(j).getPosition().trim())) {
                    listBeanList.add(bean.getList().get(j));
                } else {
                    i = j - 1;
                    break;
                }
            }
            parentBean.setChildList(listBeanList);
            parentBeanList.add(parentBean);
            continue;

        }
        mingxiMoBanBean.setParentBeanList(parentBeanList);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 1 && data != null) {
            mingxiMoBanBean = (MingxiMoBanBean) data.getSerializableExtra("data");
            manageData(mingxiMoBanBean);
            xjMingxiAdapter.notifyDataSetChanged(mingxiMoBanBean);
        }
    }

    /**
     * 提交数据
     */
    private void commit() {
        HashMap mainJson = new HashMap();
        mainJson.put("id", "");
        mainJson.put("date", riqi);

        HashMap org = new HashMap();
        org.put("id", UserManager.getUser((String) get(Constants.current_id, "")).bmcode);
        org.put("orgName", UserManager.getUser((String) get(Constants.current_id, "")).bmname);
        mainJson.put("org", org);

        HashMap account = new HashMap();
        account.put("name", xunjianren);
        account.put("id", UserManager.getUser((String) get(Constants.current_id, "")).ryid);
        mainJson.put("account", account);

        selImageList.clear();
        List<MingxiMoBanBean.ListBean> jiankkElefailinsprecDivList = new ArrayList();
        List<UpImgInfoBean> upImgInfoBeanList = new ArrayList<>();
//        for (MingxiMoBanBean.ParentBean parentBean : mingxiMoBanBean.getParentBeanList()) {
            for (MingxiMoBanBean.ListBean listBean : mingxiMoBanBean.getList()) {
                listBean.setIsNewRecord(true);
                listBean.setId(listBean.getId() + System.currentTimeMillis());
                if (null != listBean.getImages()) {
                    for (ImageItem image : listBean.getImages()) {
                        UpImgInfoBean imgInfoBean = new UpImgInfoBean();
                        imgInfoBean.setBusniessId(listBean.getId());
                        imgInfoBean.setContentType("jiankkElefailinsprecDiv");
                        imgInfoBean.setFileType("img");
                        String uuid = UUID.randomUUID().toString();
                        imgUUIDs.add(uuid);
                        imgInfoBean.setId(uuid);
                        upImgInfoBeanList.add(imgInfoBean);
                    }
                    selImageList.addAll(listBean.getImages());
                }
                jiankkElefailinsprecDivList.add(listBean);
            }
//        }
        mainJson.put("jiankkElefailinsprecDivList", jiankkElefailinsprecDivList);
        HashMap<String, String> hashMap = new HashMap();
        hashMap.put("mainJson", new Gson().toJson(mainJson));
        hashMap.put("sysAttachmentsJson", GsonUtil.bean2Json(upImgInfoBeanList));
        HttpSender sender = new HttpSender(this, baseUrl, Urls.jiankkElefailinsprecUploadData);
        sender.requestPost(hashMap, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                upImag();
            }
        });
    }

    private void upImag() {
        if (selImageList != null && selImageList.size() != 0) {
            List<File> list = new ArrayList<>();
            for (ImageItem imageItem : selImageList) {
                File file = new File(imageItem.path);
                list.add(file);
            }
            List<Map<String, String>> params = new ArrayList<>();
            for (String imgUUID : imgUUIDs) {
                Map<String, String> map = new HashMap<>();
                map.put("id", imgUUID);
                map.put("type", "jiankkElefailinsprecDiv");
                params.add(map);
            }
            LuBanHelper luBanHelper = new LuBanHelper(XjMingXiMuBanActivity.this, list, params);
            luBanHelper.compression(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(String response, int id) {
                    Toast.makeText(XjMingXiMuBanActivity.this, "提交成功111", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
        } else {
            Toast.makeText(XjMingXiMuBanActivity.this, "提交成功222", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
}
